<!-- 证照管理 -->
<template>
  <div v-loading="loading" class="certificate-container">
    <CustomTabs :tabList="classNameList" :activeName="activeName" @tabSelect="handelTabSelected" />
    <div class="mg-b-8">
      <div class="tab">
        <div
          v-for="item in tabList"
          :key="item.categoryId"
          :class="['tab-item', { 'active-tab': activeTab?.category === item?.category }]"
          @click="changeTab(item)"
        >
          {{ item?.category }}
        </div>
      </div>
    </div>
    <div class="flex-center">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <!-- <px-form-item label="科室" prop="department">
          <px-select v-model="queryParams.department" style="width: 260px" placeholder="请选择科室" clearable>
            <px-option v-for="item in classNameList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item> -->
        <px-form-item label="证照分类" prop="classification">
          <px-select v-model="queryParams.classification" style="width: 260px" placeholder="请选择证照分类" clearable @change="handleTypeChange">
            <px-option v-for="item in classificationList" :key="item.licenseCategoryId" :label="item.category" :value="item.licenseCategoryId" />
          </px-select>
        </px-form-item>
        <px-form-item label="证照名称" prop="name">
          <!-- <px-input v-model="queryParams.name" style="width: 260px" placeholder="请输入证照名称" clearable /> -->
          <px-select v-model="queryParams.name" style="width: 260px" placeholder="请选择证照名称" clearable>
            <px-option v-for="item in nameList" :key="item.value" :label="item.name" :value="item.name" />
          </px-select>
        </px-form-item>
        <px-form-item label="状态" prop="state">
          <px-select v-model="queryParams.state" style="width: 260px" placeholder="请选择状态" clearable>
            <px-option v-for="item in stateList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
    </div>
    <div class="flex-center mg-b-8">
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_ADD'" type="primary" @click="handleAdd">新增</px-button>
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_DOWNLOAD_TEMPLATE'" type="primary" plain @click="handleDownloadTemplate"
        >下载模板</px-button
      >
      <px-upload action="#" :http-request="handleImport" :show-file-list="false" accept=".xlsx, xls" style="margin: 0 16px">
        <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_IMPORT'" type="primary" plain>批量导入</px-button>
      </px-upload>
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_DOWNLOAD'" type="primary" plain @click="handleExport">导出</px-button>
      <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_BATCH_DELETE'" plain @click="handleBatchDelete">删除</px-button>
    </div>
    <div class="table-content">
      <px-table height="calc(100vh - 400px)" :data="tableData" size="small" border class="common-table" @selection-change="handleSelect">
        <px-table-column type="selection" width="55" />
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="licenseCategoryName" label="证照类型" min-width="120" show-overflow-tooltip />
        <px-table-column prop="departmentName" label="科室" min-width="120" show-overflow-tooltip />
        <px-table-column prop="name" label="证照名称" min-width="120" show-overflow-tooltip />
        <px-table-column prop="stateName" label="状态" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span :style="{ color: colorMap[scope.row.state] }">{{ stateMap[scope.row.state] }}</span>
          </template>
        </px-table-column>
        <!-- 设备证照 -->
        <template v-if="activeTab.categoryType === 'DEVICE'">
          <px-table-column prop="deviceName" label="设备名称" min-width="120" show-overflow-tooltip />
          <px-table-column prop="deviceCode" label="设备编码" min-width="120" show-overflow-tooltip />
        </template>

        <!-- 人员证照 -->
        <template v-if="activeTab.categoryType === 'CERT'">
          <px-table-column prop="holder" label="持证人员" min-width="120" show-overflow-tooltip />
          <px-table-column prop="org" label="部门" min-width="120" show-overflow-tooltip />
          <px-table-column prop="idCard" label="身份证号" min-width="120" show-overflow-tooltip />
          <px-table-column prop="mobile" label="手机号" min-width="120" show-overflow-tooltip />
        </template>

        <px-table-column prop="institution" label="颁证机构" min-width="120" show-overflow-tooltip />
        <px-table-column prop="releaseTime" label="颁证日期" min-width="120" show-overflow-tooltip />
        <px-table-column prop="dueTime" label="有效期" min-width="120" show-overflow-tooltip />
        <px-table-column prop="durationPeriod" label="办证时长(天)" min-width="160" show-overflow-tooltip />
        <px-table-column prop="updateTime" label="更新时间" min-width="140" show-overflow-tooltip />
        <px-table-column prop="updateByName" label="更新人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="createTime" label="创建时间" min-width="140" show-overflow-tooltip />
        <px-table-column prop="createByName" label="创建人" min-width="120" show-overflow-tooltip />
        <!-- <px-table-column prop="documentId" label="附件" min-width="300" show-overflow-tooltip>
          <template #default="scope">
            <px-button v-if="scope.row.documentId" link type="primary" @click="handlePreviewImg(scope.row.documentId[0])">
              {{ scope.row.documentId[0]?.originalName }}
            </px-button>
            <span v-else>--</span>
          </template>
        </px-table-column> -->
        <px-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <px-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="查看" placement="top">
              <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_VIEW'" link icon="View" type="primary" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button
                v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_EDIT'"
                link
                icon="EditPen"
                type="primary"
                @click="handleEdit(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="注销" placement="top">
              <px-button
                v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_LOGOUT'"
                link
                icon="SwitchButton"
                type="primary"
                @click="handleDrop(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button
                v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE_DELETE'"
                link
                icon="Delete"
                type="danger"
                @click="handleDelete(scope.row)"
              />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        class="table-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>

    <!-- 新增、编辑 -->
    <div v-if="editDialogVisible">
      <AddOrEdit
        v-model:visible="editDialogVisible"
        :title="editDialogTitle"
        :classNameList="classNameList"
        :certificateTypeList="classificationList"
        :handleType="handleType"
        :activeTab="activeTab"
        :rowData="rowData"
        @saveAction="handleQuery"
      />
    </div>

    <!-- 查看 -->
    <div v-if="viewDialogVisible">
      <View v-model:visible="viewDialogVisible" :activeTab="activeTab" :rowData="rowData" />
    </div>

    <!-- 图片预览 -->
    <px-image-viewer v-if="showImagePreview" :zoom-rate="1" :url-list="imgPreviewList" @close="closePreview" />
  </div>
</template>

<script setup>
import { queryCurrentClassList } from "@/api/common";
import {
  deleteCertificateAPI,
  getCategoryListAPI,
  getCertificateListAPI,
  logOffCertificateAPI,
  uploadAPI,
  licenseNameSelectsAPI,
  batchDelLicenceAPI
} from "@/api/knowledge/certificate";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, ref, toRefs, getCurrentInstance } from "vue";
import AddOrEdit from "./component/AddOrEdit.vue";
import View from "./component/View.vue";
import CustomTabs from "@/components/Tabs/index.vue";

defineOptions({
  name: "ALL_KNOWLEDGE_CERTIFICATEMANAGE_CERTIFICATE"
});

const { proxy } = getCurrentInstance();

const formRef = ref(null);
const classNameList = ref([]);
const nameList = ref([]);
const activeName = ref("");

const state = reactive({
  tabList: [],
  queryParams: {
    department: "",
    classification: "",
    name: "",
    state: ""
  },
  classificationList: [],
  loading: false,
  tableData: [],
  total: 1,
  pageNum: 1,
  pageSize: 20,
  editDialogVisible: false,
  editDialogTitle: "",
  viewDialogVisible: false,
  handleType: "",
  activeTab: {},
  selectedTableData: [],
  rowData: {},
  showImagePreview: false,
  imgPreviewList: []
});
const {
  tabList,
  queryParams,
  classificationList,
  loading,
  tableData,
  total,
  pageNum,
  pageSize,
  editDialogVisible,
  viewDialogVisible,
  editDialogTitle,
  handleType,
  activeTab,
  rowData,
  showImagePreview,
  imgPreviewList
} = toRefs(state);

// 证照状态
const stateMap = {
  N: "正常",
  O: "临期",
  E: "到期",
  P: "过期",
  C: "注销"
};
// 证照颜色
const colorMap = {
  N: "#10B981",
  O: "#F59E0B",
  E: "#FF771E",
  P: "#EF4444",
  C: "#903999"
};
// 证照状态列表
const stateList = [
  {
    label: "正常",
    value: "N"
  },
  {
    label: "临期",
    value: "O"
  },
  {
    label: "到期",
    value: "E"
  },
  {
    label: "过期",
    value: "P"
  },
  {
    label: "注销",
    value: "C"
  }
];

const changeTab = tab => {
  formRef.value.resetFields();
  state.activeTab = tab;
  state.classificationList = tab.children;
  handleQuery();
  getNameList();
};

onMounted(() => {
  getClassNameSelect();
  getTabList();
});

// 获取科室下拉框数据
const getClassNameSelect = async () => {
  try {
    const res = await queryCurrentClassList();
    if (res?.length) {
      res?.forEach(i => {
        i.label = i.itemName;
        i.name = i.value;
      });
      classNameList.value = res;
      activeName.value = res?.[0]?.name || "";
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取证照名称下拉框数据
const getNameList = async () => {
  try {
    let params = {
      categoryId: state?.activeTab?.categoryId || null,
      licenseCategoryId: state?.queryParams.classification || null
    };
    nameList.value = await licenseNameSelectsAPI(params);
  } catch (error) {}
};

// 获取tab
const getTabList = async () => {
  try {
    state.loading = true;
    const params = {
      categoryId: null,
      category: "",
      categoryType: ""
    };
    const res = await getCategoryListAPI(params);
    state.tabList = res;
    state.activeTab = res[0];
    state.classificationList = res[0].children;
    handleQuery();
    getNameList();
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 切换tab
const handelTabSelected = () => {};

// 查询
const handleQuery = async () => {
  try {
    state.loading = true;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      topCategoryId: state.activeTab.categoryId,
      categoryId: state.queryParams.classification,
      // department: state.queryParams.department,
      name: state.queryParams.name,
      state: state.queryParams.state
    };
    const res = await getCertificateListAPI(params);
    state.tableData = res.data;
    state.total = res.total;
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const handleSelect = val => {
  state.selectedTableData = val;
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

const handleTypeChange = () => {
  state.queryParams.name = "";
  getNameList();
};

// 下载模板
const handleDownloadTemplate = () => {
  const fileUrl = "/models/证照导入模板.xlsx";

  // 创建一个隐藏的a标签
  const link = document.createElement("a");
  link.href = fileUrl;

  // 将a标签添加到DOM并触发点击事件
  document.body.appendChild(link);
  link.click();

  // 移除a标签
  document.body.removeChild(link);
};

// 批量导入
const handleImport = async options => {
  try {
    state.loading = true;
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    await uploadAPI(formData);
    PxMessage.success("批量导入成功");
    handleQuery();
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const handlePreviewImg = img => {
  state.imgPreviewList = [img.fileUrl];
  state.showImagePreview = true;
};

const closePreview = () => {
  state.showImagePreview = false;
};

// 查看
const handleView = row => {
  // state.editDialogTitle = "查看";
  // state.handleType = "VIEW";
  state.rowData = row;
  // state.editDialogVisible = true;
  state.viewDialogVisible = true;
};

// 新增
const handleAdd = () => {
  state.editDialogTitle = "新增";
  state.handleType = "ADD";
  state.rowData = {};
  state.editDialogVisible = true;
};

// 编辑
const handleEdit = row => {
  state.editDialogTitle = "编辑";
  state.handleType = "EDIT";
  state.rowData = row;
  state.editDialogVisible = true;
};

// 注销
const handleDrop = row => {
  PxMessageBox.confirm("是否注销该证照", "注销", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const params = {
        id: row.id
      };
      await logOffCertificateAPI(params);
      handleQuery();
      PxMessage.success("注销成功");
    } catch (error) {
      console.log(error);
    }
  });
};

const deleteCertificate = params => {
  PxMessageBox.confirm("是否确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await deleteCertificateAPI(params);
      handleQuery();
      PxMessage.success("删除成功");
    } catch (error) {
      console.log(error);
    }
  });
};
// 导出
const handleExport = () => {
  const params = {
    pageNum: state.pageNum,
    pageSize: state.pageSize,
    topCategoryId: state.activeTab.categoryId,
    categoryId: state.queryParams.classification,
    // department: state.queryParams.department,
    name: state.queryParams.name,
    state: state.queryParams.state
  };
  proxy.download("post", "/dms/api/v1/license/exportLicense", params, "证照台账.xlsx");
};

const batchDelLicence = params => {
  PxMessageBox.confirm("是否确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await batchDelLicenceAPI(params);
      handleQuery();
      PxMessage.success("删除成功");
    } catch (error) {
      console.log(error);
    }
  });
};
// 批量删除
const handleBatchDelete = () => {
  if (state.selectedTableData.length === 0) {
    PxMessage.warning("请选择要删除的数据");
    return;
  }
  const params = {
    ids: state.selectedTableData.map(item => item.id)
  };
  batchDelLicence(params);
};

// 删除
const handleDelete = row => {
  deleteCertificate({ id: row.id });
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/certificateManage/scss/common.scss");

.tab {
  display: flex;
  align-items: center;
  height: 44px;
  margin-bottom: 16px;
  // background: #f4f4f4;
  border-radius: 4px;

  .tab-item {
    height: 36px;
    padding: 0 20px;
    line-height: 36px;
    text-align: center;
    cursor: pointer;
    background: #f4f4f4;

    &:nth-child(1) {
      border-radius: 4px 0 0 4px;
    }

    &:last-child {
      border-radius: 0 4px 4px 0;
    }

    &:hover {
      color: #fff;
      background: #4089f7;
    }
  }

  .active-tab {
    color: #fff;
    background: #4089f7;
    border-radius: 4px;
    box-shadow: 0 2px 4px 0 #b5d2fe;
  }
}
</style>
